package collector

import (
	"database/sql"
	"log/slog"

	"github.com/prometheus/client_golang/prometheus"
)

const (
	// Scrape query.
	sessionsMaxQuery    = `select SF_GET_PARA_VALUE(2,'MAX_SESSIONS')`
	sessionsTotalQuery  = `select count(*) from v$sessions`
	sessionsActiveQuery = `select count(*) from v$sessions where state='ACTIVE'`

	// Subsystem.
	sessionStatus = "session_status"
)

// 定义metricsDesc
var (
	sessionMaxDesc = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, sessionStatus, "max_sessions"),
		"The number of max session in DM.",
		nil, nil,
	)
	sessionTotalDesc = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, sessionStatus, "total_sessions"),
		"The  number of  current total  sessions in DM.",
		nil, nil,
	)
	sessionAcitveDesc = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, sessionStatus, "active_sessions"),
		"The number of current active session in DM.",
		nil, nil,
	)
)

type SessionStatus struct{}

// Name of the Scraper. Should be unique.
func (SessionStatus) Name() string {
	return "sessions"
}
func (SessionStatus) Scrape(db *sql.DB, ch chan<- prometheus.Metric, backupPath string, logger *slog.Logger) error {
	var (
		sessionsMax, sessionsTotal, sessionsActive int
		err                                        error
	)
	err = db.QueryRow(sessionsMaxQuery).Scan(&sessionsMax)
	if err != nil {
		return err
	}
	err = db.QueryRow(sessionsTotalQuery).Scan(&sessionsTotal)
	if err != nil {
		return err
	}
	err = db.QueryRow(sessionsActiveQuery).Scan(&sessionsActive)
	if err != nil {
		return err
	}
	ch <- prometheus.MustNewConstMetric(
		sessionMaxDesc, prometheus.GaugeValue, float64(sessionsMax),
	)
	ch <- prometheus.MustNewConstMetric(
		sessionTotalDesc, prometheus.GaugeValue, float64(sessionsTotal),
	)
	ch <- prometheus.MustNewConstMetric(
		sessionAcitveDesc, prometheus.GaugeValue, float64(sessionsActive),
	)
	return nil
}

func init() {
	RegisterScraper("sessions", SessionStatus{})
}

var _ Scraper = SessionStatus{}
